<template>
    <div class="cultural-info-list-container">
        <h2 class="section-title">文化资讯管理</h2>
        
        <!-- 操作按钮区域 -->
        <div class="action-bar">
            <router-link to="/home/add-cultural-info">
                <el-button type="primary">添加文化资讯</el-button>
            </router-link>
            <el-input v-model="searchQuery" placeholder="搜索文化资讯" style="width: 220px; margin-left: 10px;" clearable @keyup.enter="searchCulturalInfo">
                <template #prefix>
                    <el-icon><search /></el-icon>
                </template>
            </el-input>
        </div>
        
        <!-- 文化资讯表格 -->
        <el-table :data="allCulturalInfo" stripe style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="资讯标题" width="200"></el-table-column>
            <el-table-column label="资讯图片" width="120">
                <template #default="scope">
                    <el-image 
                        :src="getImageUrl(scope.row.image)" 
                        style="width: 60px; height: 60px;" 
                        :preview-src-list="[getImageUrl(scope.row.image)]"
                        fit="cover"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="expertName" label="专家" width="100"></el-table-column>
            <el-table-column prop="description" label="资讯描述">
                <template #default="scope">
                    <el-tooltip :content="scope.row.description" placement="top">
                        <div class="description-text">{{ scope.row.description }}</div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="editCulturalInfo(scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="confirmDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalItems"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            ></el-pagination>
        </div>
        
        <!-- 编辑文化资讯弹窗 -->
        <el-dialog
            v-model="editDialogVisible"
            title="编辑文化资讯"
            width="60%"
            destroy-on-close
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :before-close="handleDialogClose">
            <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="100px" class="cultural-info-form">
                <!-- 资讯标题 -->
                <el-form-item label="资讯标题" prop="title">
                    <el-input v-model="editForm.title" placeholder="请输入资讯标题"></el-input>
                </el-form-item>
                
                <!-- 专家姓名 -->
                <el-form-item label="专家姓名" prop="expertName">
                    <el-input v-model="editForm.expertName" placeholder="请输入专家姓名"></el-input>
                </el-form-item>
                
                <!-- 资讯图片 -->
                <el-form-item label="资讯图片" prop="image">
                    <el-upload
                        class="cultural-info-image-uploader"
                        :action="null"
                        :http-request="handleUploadRequest"
                        :show-file-list="false"
                        :before-upload="beforeImageUpload">
                        <img v-if="editForm.image" :src="getImagePreview(editForm.image)" class="cultural-info-image">
                        <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                    <span class="form-item-tip">建议尺寸：800x600像素，大小不超过2MB</span>
                </el-form-item>
                
                <!-- 专家头像 -->
                <el-form-item label="专家头像" prop="expertAvatar">
                    <el-upload
                        class="expert-avatar-uploader"
                        :action="null"
                        :http-request="handleExpertAvatarUpload"
                        :show-file-list="false"
                        :before-upload="beforeImageUpload">
                        <img v-if="editForm.expertAvatar" :src="getImagePreview(editForm.expertAvatar)" class="expert-avatar">
                        <el-icon v-else class="upload-icon"><Plus /></el-icon>
                    </el-upload>
                    <span class="form-item-tip">建议尺寸：200x200像素，大小不超过1MB</span>
                </el-form-item>
                
                <!-- 资讯描述 -->
                <el-form-item label="资讯描述" prop="description">
                    <el-input 
                        v-model="editForm.description" 
                        type="textarea" 
                        :rows="4" 
                        placeholder="请输入资讯描述，详细介绍文物的历史背景和文化价值"
                    ></el-input>
                </el-form-item>
                
                <!-- 专家点评 -->
                <el-form-item label="专家点评" prop="expertComment">
                    <el-input 
                        v-model="editForm.expertComment" 
                        type="textarea" 
                        :rows="3" 
                        placeholder="请输入专家对该文物的专业点评"
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitEditForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <RouterView/>  
</template>

<script setup>
// 导入所需的API和Vue组合式API
import api from '@/assets/js/api.js';
import { ref, onMounted, computed, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 定义响应式数据
const allCulturalInfo = ref([]); // 所有文化资讯数据
const loading = ref(true); // 加载状态
const searchQuery = ref(''); // 搜索关键词
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const totalItems = ref(0); // 总记录数
const editDialogVisible = ref(false); // 编辑弹窗是否可见
const editFormRef = ref(null); // 编辑表单引用

// 编辑表单数据
const editForm = reactive({
    id: null,
    title: '',
    expertName: '',
    image: '',
    expertAvatar: '',
    description: '',
    expertComment: ''
});

// 表单验证规则
const formRules = {
    title: [
        { required: true, message: '请输入资讯标题', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在2到100个字符之间', trigger: 'blur' }
    ],
    expertName: [
        { required: true, message: '请输入专家姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入资讯描述', trigger: 'blur' },
        { min: 10, max: 1000, message: '描述长度在10到1000个字符之间', trigger: 'blur' }
    ],
    expertComment: [
        { required: true, message: '请输入专家点评', trigger: 'blur' },
        { min: 10, max: 500, message: '点评长度在10到500个字符之间', trigger: 'blur' }
    ]
};

// 获取文化资讯列表数据
async function culturalInfoList() {
    loading.value = true;
    try {
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value,
        };

        if (searchQuery.value) {
            params.query = searchQuery.value;
        }

        const result = await api.getCulturalInfoWithPagination(params);

        if (result.code === 200) {
            allCulturalInfo.value = result.data.records;
            totalItems.value = result.data.total;
            console.log('文化资讯数据加载成功', allCulturalInfo.value);
        } else {
            ElMessage.error('获取文化资讯数据失败: ' + result.message);
        }
    } catch (error) {
        console.error('请求文化资讯列表异常:', error);
        ElMessage.error('获取文化资讯数据失败，请稍后重试');
    } finally {
        loading.value = false;
    }
}

// 搜索文化资讯
const searchCulturalInfo = () => {
    currentPage.value = 1;
    culturalInfoList();
};

// 分页大小改变
const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    culturalInfoList();
};

// 当前页改变
const handleCurrentChange = (val) => {
    currentPage.value = val;
    culturalInfoList();
};

// 编辑文化资讯
const editCulturalInfo = (row) => {
    Object.assign(editForm, row);
    editDialogVisible.value = true;
};

// 确认删除
const confirmDelete = (row) => {
    ElMessageBox.confirm(`确定要删除文化资讯 "${row.title}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        deleteCulturalInfo(row.id);
    }).catch(() => {});
};

// 删除文化资讯
const deleteCulturalInfo = async (id) => {
    try {
        const result = await api.deleteCulturalInfo(id);
        if (result.code === 200) {
            ElMessage.success('删除成功');
            culturalInfoList();
        } else {
            ElMessage.error('删除失败: ' + result.message);
        }
    } catch (error) {
        console.error('删除文化资讯异常:', error);
        ElMessage.error('删除失败，请稍后重试');
    }
};

// 提交编辑表单
const submitEditForm = async () => {
    if (!editFormRef.value) return;
    
    try {
        await editFormRef.value.validate();
        
        const result = await api.updateCulturalInfo(editForm);
        if (result.code === 200) {
            ElMessage.success('更新成功');
            editDialogVisible.value = false;
            culturalInfoList();
        } else {
            ElMessage.error('更新失败: ' + result.message);
        }
    } catch (error) {
        console.error('更新文化资讯异常:', error);
        ElMessage.error('更新失败，请稍后重试');
    }
};

// 处理弹窗关闭
const handleDialogClose = (done) => {
    ElMessageBox.confirm('确定要关闭吗？未保存的数据将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        done();
    }).catch(() => {});
};

// 获取图片URL
const getImageUrl = (imagePath) => {
    if (!imagePath) return '';
    return imagePath.startsWith('http') ? imagePath : `http://localhost:8080/${imagePath}`;
};

// 获取图片预览URL
const getImagePreview = (imagePath) => {
    if (!imagePath) return '';
    return imagePath.startsWith('http') ? imagePath : `http://localhost:8080/${imagePath}`;
};

// 处理图片上传
const handleUploadRequest = async (options) => {
    try {
        const result = await api.uploadFile(options.file);
        if (result.code === 200) {
            editForm.image = result.data;
            ElMessage.success('图片上传成功');
        } else {
            ElMessage.error('图片上传失败: ' + result.message);
        }
    } catch (error) {
        console.error('图片上传异常:', error);
        ElMessage.error('图片上传失败，请稍后重试');
    }
};

// 处理专家头像上传
const handleExpertAvatarUpload = async (options) => {
    try {
        const result = await api.uploadFile(options.file);
        if (result.code === 200) {
            editForm.expertAvatar = result.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('头像上传失败: ' + result.message);
        }
    } catch (error) {
        console.error('头像上传异常:', error);
        ElMessage.error('头像上传失败，请稍后重试');
    }
};

// 上传前验证
const beforeImageUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

// 页面加载时获取数据
onMounted(() => {
    culturalInfoList();
});
</script>

<style scoped>
.cultural-info-list-container {
    padding: 20px;
}

.section-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}

.action-bar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.description-text {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.cultural-info-form .form-item-tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
}

.cultural-info-image-uploader .cultural-info-image {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 6px;
}

.expert-avatar-uploader .expert-avatar {
    width: 60px;
    height: 60px;
    display: block;
    border-radius: 50%;
}

.upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: .3s;
}

.upload-icon:hover {
    border-color: #409EFF;
}

.dialog-footer {
    text-align: right;
}
</style>